﻿using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using System.Xml;
using System.Net;
using System.Web;

namespace CWS.Twitter4Umbraco
{
    public class XSLTExtensions
    {

        /// <summary>
        /// Format Twitter Date
        /// </summary>
        /// <param name="twitterDate">Thu Nov 08 19:07:37 +0000 2007</param>
        /// <returns>2007-11-08T19:07:37</returns>
        public static string FormatTwitterDate(string twitterDate)
        {
            DateTime parsedDate;
            if (DateTime.TryParseExact(twitterDate, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out parsedDate))
            {
                return parsedDate.ToLocalTime().ToString("s");
            }
            return "1900-01-01T00:00:00";
        }
        /// <summary>
        /// Format the tweet, with @reply links, #searches and external URLs
        /// </summary>
        /// <param name="twitterText">The original tweet</param>
        /// <returns>The new text with <a> tags added</returns>
        public static string FormatUrls(string twitterText)
        {

            // Chris Houston's code to fix the regex 
            // twitter user: @readingdancer
            try
            {
                var urlRegex = new Regex(@"(http\:\/\/\S+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                var urlSecureRegex = new Regex(@"(https\:\/\/\S+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                var replyRegex = new Regex(@"(^|\s)@(\w+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                var searchRegex = new Regex(@"(^|\s)#(\w+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                twitterText = urlRegex.Replace(twitterText, " <a href=\"$1\">$1</a>");                                  // Replace URLs
                twitterText = urlSecureRegex.Replace(twitterText, " <a href=\"$1\">$1</a>");                            // Replace https URLs
                twitterText = replyRegex.Replace(twitterText, " <a href=\"http://twitter.com/$2\">@$2</a>");            // Replace @ replies
                twitterText = searchRegex.Replace(twitterText, " <a href=\"http://twitter.com/search?q=$2\">#$2</a>");  // Replace hash tags

                return twitterText;
            }
            catch (Exception)
            {
                //Return the original string
                return twitterText;
            }
        }

    }
}